<template>
  <div class="address-management">
    <div class="page-header">
      <h1>地址管理</h1>
      <el-button class="add-btn" type="primary" @click="openEditModal()">
        <el-icon>
          <Plus/>
        </el-icon>
        新增地址
      </el-button>
    </div>

    <!-- 地址表格 -->
    <el-card class="address-card">
      <el-table :data="addresses" border style="width: 100%">
        <el-table-column align="center" label="联系人" prop="consignee"></el-table-column>
        <el-table-column align="center" label="联系地址">
          <template #default="scope">
            {{ getFullAddress(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="联系电话" prop="phone"></el-table-column>
        <el-table-column align="center" label="默认地址" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.isDefault" type="primary">默认</el-tag>
            <el-button
                v-else
                size="small"
                type="text"
                @click="setDefaultAddress(scope.row.id)"
            >
              设为默认
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="200">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openEditModal(scope.row)">
              <el-icon>
                <Edit/>
              </el-icon>
              编辑
            </el-button>
            <el-button
                :disabled="scope.row.isDefault"
                size="small"
                type="danger"
                @click="deleteAddress(scope.row.id)"
            >
              <el-icon>
                <Delete/>
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 -->
    <div class="pagination mt-4">
      <span class="mr-2">共 {{ addresses.length }} 条</span>
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="addresses.length"
          layout="prev, pager, next"
      ></el-pagination>
    </div>

    <!-- 编辑/新增地址模态框 -->
    <el-dialog v-model="editModalVisible" :title="isEditing ? '编辑地址' : '新增地址'" :width="600">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="联系人" prop="consignee">
          <el-input v-model="form.consignee" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" required>
          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item prop="province">
                <el-input v-model="form.province" placeholder="省"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="city">
                <el-input v-model="form.city" placeholder="市"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="district">
                <el-input v-model="form.district" placeholder="区/县"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input
              v-model="form.detail"
              :rows="3"
              placeholder="请输入详细地址（街道、门牌号等）"
              type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="form.isDefault" :false-value="0" :true-value="1">
            设为默认地址
          </el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeEditModal()">取消</el-button>
        <el-button type="primary" @click="saveAddress()">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit, Plus} from '@element-plus/icons-vue';
import http from "@/request/Http.js";

// 地址数据
const addresses = ref([]);

// 分页
const currentPage = ref(1);
const pageSize = ref(10);

// 编辑模态框状态
const editModalVisible = ref(false);
const isEditing = ref(false);
const formRef = ref(null);

// 表单数据
const form = reactive({
  id: null,
  consignee: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  isDefault: 0,
  userId: 1
});

// 表单验证规则
const rules = reactive({
  consignee: [
    {required: true, message: '请输入收货人姓名', trigger: 'blur'},
    {min: 2, max: 10, message: '姓名长度在2到10个字符', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号码', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ],
  province: [
    {required: true, message: '请输入省份', trigger: 'blur'}
  ],
  city: [
    {required: true, message: '请输入城市', trigger: 'blur'}
  ],
  district: [
    {required: true, message: '请输入区/县', trigger: 'blur'}
  ],
  detail: [
    {required: true, message: '请输入详细地址', trigger: 'blur'},
    {min: 5, max: 100, message: '详细地址长度在5到100个字符', trigger: 'blur'}
  ]
});

// 获取完整地址
const getFullAddress = (address) => {
  if (!address) return '';
  const {province, city, district, detail} = address;
  return `${province}${city}${district}${detail}`;
};

// 加载地址列表
const loadAddresses = async () => {
  try {
    const response = await http.get(`/address/user`);
    console.log('地址列表响应:', response);
    if (response && response.code === 200) {
      addresses.value = response.data || [];
    } else {
      ElMessage.error('获取地址列表失败');
    }
  } catch (error) {
    console.error('加载地址列表失败:', error)
    ElMessage.error('加载地址列表失败');
  }
};

// 设置默认地址
const setDefaultAddress = async (addressId) => {
  try {
    const response = await http.put(`/address/setDefault/${addressId}`,
    );

    if (response && response.code === 200) {
      ElMessage.success('设置默认地址成功');
      await loadAddresses(); // 刷新地址列表
    } else {
      ElMessage.error(response.message || '设置默认地址失败');
    }
  } catch (error) {
    console.error('设置默认地址失败:', error);
    ElMessage.error('设置默认地址失败');
  }
};

// 组件挂载时加载地址
onMounted(() => {
  loadAddresses();
});

// 打开编辑模态框
const openEditModal = (address = null) => {
  if (address) {
    // 编辑模式
    isEditing.value = true;
    form.id = address.id;
    form.consignee = address.consignee || '';
    form.phone = address.phone || '';
    form.province = address.province || '';
    form.city = address.city || '';
    form.district = address.district || '';
    form.detail = address.detail || '';
    form.isDefault = address.isDefault || 0;
    form.userId = address.user_id || 1;
  } else {
    // 新增模式
    isEditing.value = false;
    resetForm();
  }
  editModalVisible.value = true;
};

// 关闭编辑模态框
const closeEditModal = () => {
  editModalVisible.value = false;
  resetForm();
};

// 重置表单 - 修复这里
const resetForm = () => {
  // 清空所有表单字段
  form.id = null;
  form.consignee = '';
  form.phone = '';
  form.province = '';
  form.city = '';
  form.district = '';
  form.detail = '';
  form.isDefault = 0;
  form.userId = 1;

  // 重置表单验证状态
  if (formRef.value) {
    // 使用 nextTick 确保 DOM 更新后再重置表单
    setTimeout(() => {
      formRef.value.resetFields();
    }, 0);
  }
};

// 保存地址
const saveAddress = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 准备提交的数据
        const submitData = {
          id: form.id,
          consignee: form.consignee,
          phone: form.phone,
          province: form.province,
          city: form.city,
          district: form.district,
          detail: form.detail,
          isDefault: form.isDefault,
          userId: form.userId
        };

        if (isEditing.value) {
          // 更新地址
          const response = await http.put('/address', submitData);
          if (response && response.code === 200) {
            ElMessage.success('地址更新成功');
            await loadAddresses();
          } else {
            ElMessage.error(response.message || '更新地址失败');
          }
        } else {
          // 新增地址
          const response = await http.post('/address', submitData);
          if (response && response.code === 200) {
            ElMessage.success('地址添加成功');
            await loadAddresses();
          } else {
            ElMessage.error(response.message || '新增地址失败');
          }
        }
        editModalVisible.value = false;
        resetForm();
      } catch (error) {
        console.error('保存地址失败:', error);
        ElMessage.error('保存地址失败');
      }
    }
  });
};

// 删除地址
const deleteAddress = (id) => {
  ElMessageBox.confirm(
      '确定要删除该地址吗？',
      '删除地址',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        try {
          const userId = 1;
          const response = await http.delete(`/address/${id}?userId=${userId}`);
          if (response && response.code === 200) {
            ElMessage.success('地址已删除');
            await loadAddresses();
          } else {
            ElMessage.error(response.message || '删除地址失败');
          }
        } catch (error) {
          console.error('删除地址失败:', error);
          ElMessage.error('删除地址失败');
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
};
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.add-btn {
  display: flex;
  align-items: center;
}

.address-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  border-radius: 4px;
  overflow: hidden;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}
</style>